package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
//创建要实现HandlerInterceptor接口
//创建的拦截器需要在拦截器的注册器上注册才会生效的
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Map<String, Object> jwt = JwtUtils.parseJwt(token);
        if (ObjectUtils.isEmpty(token) || jwt == null){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            //也可以这样写状态码,是主流，可以一眼看出来是给响应设置状态码
            //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //返回true是表示不用拦截请求，请求通过
        return true;
    }
}
